package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.applicationservice.base.ApplicationBaseService;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.RemidDto;
import com.authine.cloudpivot.ext.enums.order.OrderCustomerStatusEnum;
import com.authine.cloudpivot.ext.enums.order.OrderGoodsStatusEnum;
import com.authine.common.json.JsonUtils;
import com.authine.mvp.app.launcher.common.TableHelper;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.domain.utills.DateUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.*;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * 个人中心-消息提醒
 */
@Path("RemindService")
@Slf4j
public class RemindService extends ApplicationBaseService {
    private NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);
    private TableHelper tableHelper = ApplicationContextUtils.getBean(TableHelper.class);

    /**
     * 报价提醒列表
     *
     * @param dto
     * @return
     */
    @Path("quotationRemindList")
    @POST
    @Operation(summary = "消息提醒-报价提醒列表", tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> quotationRemindList(@Parameter RemidDto dto) {
        log.info("------------------------报价提醒列表 quotationRemindList Param：{}------------------------", JSONObject.toJSONString(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        String tableName = getTableName(AppConst.SOURCING_CENTER, ModelConst.T_QUOTATION_GOODS);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select * from " + tableName + " where quotation_goods_status in ('0','2') ");//新建，已退回状态
        countSql.append("select count(*) from " + tableName + " where quotation_goods_status in ('0','2') ");
        //拼接参数
        if (StringUtils.isNotBlank(dto.getOrganizationName())) {
            whereSql.append(" and organization_company_name like :organization_company_name ");
            parameter.put("organization_company_name", "%" + dto.getOrganizationName() + "%");
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by createdTime desc");
        listSql.append(" limit " + dto.getPageIndex()*dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------报价提醒列表 quotationRemindList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        log.info("------------------------报价提醒列表 quotationRemindList whereSql：{}------------------------parameter：{}", whereSql, listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        //构建结果集
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_QUOTATION_GOODS);
        return SingleResponse.of(bOList);
    }

    /**
     * 接单提醒列表
     *
     * @param dto
     * @return
     */
    @Path("orderRemindList")
    @POST
    @Operation(summary = "消息提醒-接单提醒列表", tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> orderRemindList(@Parameter RemidDto dto) {
        log.info("------------------------接单提醒列表 orderRemindList Param：{}------------------------", JSONObject.toJSONString(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        String goodsTableName = getTableName(AppConst.ORDER_CENTER, ModelConst.T_ORDER_CUSTOMER_GOODS);
        String tableName = getTableName(AppConst.ORDER_CENTER, ModelConst.T_ORDER_CUSTOMER);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,-1);
        String date = DateUtils.getDate(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
        listSql.append("select cg.* from "+goodsTableName+" cg " +
                "inner join "+tableName+" c on cg.order_customer_id = c.id " +
                "where c.order_customer_status='"+ OrderCustomerStatusEnum.UpcomingConfirm.name() +"' and c.place_order_time<'" + date + "'");//付款后，超过24h未接单提醒
        countSql.append("select count(*) from "+goodsTableName+" cg " +
                "inner join "+tableName+" c on cg.order_customer_id = c.id " +
                "where c.order_customer_status='"+ OrderCustomerStatusEnum.UpcomingConfirm.name() +"' and c.place_order_time<'" + date + "'");
        //拼接参数
        if (StringUtils.isNotBlank(dto.getOrganizationName())) {
            whereSql.append(" and cg.customer_organization_name like :customer_organization_name ");
            parameter.put("customer_organization_name", "%" + dto.getOrganizationName() + "%");
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by cg.createdTime desc");
        listSql.append(" limit " + dto.getPageIndex()*dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------报价提醒列表 quotationRemindList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        //构建结果集
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_ORDER_CUSTOMER_GOODS);
        return SingleResponse.of(bOList);
    }

    /**
     * 个人中心—收货提醒
     */
    @Path("receiptRemindList")
    @POST
    @Operation(summary = "消息提醒-收货提醒列表",tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> receiptRemindList(@Parameter RemidDto remidDto){
        log.info("----------------个人中心—收货提醒-----------------", JSONObject.toJSONString(remidDto));
        if(null == remidDto.getPageIndex() || null == remidDto.getPageSize()){
            return SingleResponse.buildFailure("-1","参数不合法");
        }
        String tableName = getTableName(AppConst.ORDER_CENTER, ModelConst.T_ORDER_CUSTOMER_GOODS);
        String traceTableName = getTableName(AppConst.ORDER_CENTER, ModelConst.T_ORDER_TRACE);
        Map<String,Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql  = new StringBuilder();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,-5);
        String date = DateUtils.getDate(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
        listSql.append("select case when cg.logistics is null or cg.logistics = '' then ot.logistics else ot.logistics end as logistics, " +
                "case when cg.waybill is null or cg.waybill = '' then ot.waybill else ot.waybill end as waybill," +
                "case when cg.createdTime is not null then ot.createdTime else ot.createdTime end as createdTime," +
                "cg.* from " + tableName +" cg " +
                "left join "+traceTableName+" ot on cg.id = ot.order_customer_goods_id " +
                "where cg.order_customer_goods_status ='"+ OrderGoodsStatusEnum.DoneDelivery.name() +"' and ot.createdTime < '" + date + "'");
        countSql.append("select count(*) from " + tableName +" cg " +
                "left join "+traceTableName+" ot on cg.id = ot.order_customer_goods_id " +
                "where cg.order_customer_goods_status ='"+ OrderGoodsStatusEnum.DoneDelivery.name() +"' and ot.createdTime < '" + date + "'");
        if(StringUtils.isNotBlank(remidDto.getOrganizationName())){
            whereSql.append(" and cg.customer_organization_name like :customer_organization_name ");
            parameter.put("customer_organization_name", "%" + remidDto.getOrganizationName()+ "%");
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" limit " + remidDto.getPageIndex()*remidDto.getPageSize() + " ," + remidDto.getPageSize());
        log.info("-------------------------收货提醒列表 receiptRemindList oneSql:{}-------", listSql.toString());
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(),parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        }catch (DataAccessException e){
            e.printStackTrace();
        }
        BOList boList =new BOList();
        boList.setData(resultList);
        boList.setTotal(count);
        boList.setSchemaCode(ModelConst.T_ORDER_CUSTOMER_GOODS);
        return SingleResponse.of(boList);
    }
}
